//获取应用实例
var common_Js = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
var app = getApp(), fetchApi = require("../../../utils/httpPost.js")
import Dialog from '../../../component/vant/dialog/dialog';
Page({
  data: {
    imgurl: app.getImgUrl(),
    quantity1: {
      quantity: 1,
      min: 1,
      max: 20
    },
    skuMaxCount:2,
    id: 0,
    scrollTop: 0,
    imgUrls: [],//商品图片
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    scrollHeight: 0,
    btnWidth: 0,
    showDialog: false,
    goodsData: [],//商品信息
    guiges: [],//规格集合
    descContentList:[],
    appraiseCount:0,
    isShowSku:true,
    isShowSkuPop:false,
    skus:[],//sku列表
    productInfo:[],//商品基础信息
    productValue:[],//规格列表
    productAttr:[],//规格类型
    appraises: [],
    details: [],
    currentState: '',
    goBuyType: "addCart",
    skuStock:0,
    isAllCheck:false,
    chooseSkuId:'',
    chooseSkuImg:'',
    chooseSkuIndex: 0,
    chooseSkuCount: 1,//sku 当前的数量
    chooseSkuTxt:'',
    chooseSku:{},//当前选中的 sku 对象
    chooseSkuAttr:'',
    islimitCount:false,
    buyLimitCount:0,
    hasCard:false,
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    isCollect: false,
    loading: false,
    netWork: false,
    isLoading: true,
    openData:[],
    fromType: '',
    visibleModal: false, 
    product:{},
    cart_count:0,
    isCanPay:1,
    authSetModalText:
    [
      { name: '取消', },
      { name: '确认购买',  color: '#ed3f14', loading: false }
    ],
    totalPrice:0,
    ag_id:0,
  },
  onLoad: function (param) {
    console.log("商品详情参数",param)
    var that = this;
    var id = parseInt(param.id) 
    that.data.id = id;

    if(param.ag_id){
        this.data.ag_id = param.ag_id;
    }

    that.onHttpInit()
    that.data.choosedSkuId = 0;
    that.setData({
      scrollHeight: app.globalData.windowHeight+4,
      btnWidth: app.globalData.windowWidth,
      isShowSkuPop:false
    });
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/product/detail', {
      product_id: that.data.id
    }, function (res) {
      if (res.data.code == 0) {
        console.log("商品详情数据", res.data.data)
        that.data.descContentList = res.data.data.description
        that.data.productValue = res.data.data.product.productValue
        that.data.islimitCount = res.data.data.product.isLimit
        that.data.buyLimitCount = res.data.data.product.limitCount
        that.data.productAttr = res.data.data.product.productAttr
        that.data.product = res.data.data.product;
      
        that.setData({
          product:res.data.data.product,
          productAttr: res.data.data.product.productAttr,
          productValue : res.data.data.product.productValue,
          chooseSkuImg: res.data.data.product.image,
          cart_count:res.data.data.cart_count,
          productInfo: res.data.data.product,
          imgUrls: res.data.data.product.sliderImageArray,
          currentState: "1/" + res.data.data.product.sliderImageArray.length,
          skuStock:res.data.data.product.totalCount,
          isCollect: res.data.data.isCollect > 0 ? true: false,
        });
        that.setData({ isLoading: false, loading: true, netWork: true, }) 
      } else {
        console.log("商品详情数据 异常", res.data.msg)
      }
    },function(){
      that.setData({ isLoading: false, loading: true, netWork: true, }) 
    })
  },
  /**
   * 显示sku弹框
   */
  showSkuPop:function(e){
    console.log('showSkuPop e',e)
    var buytype = e.currentTarget.dataset.type;
    this.setData({
      isShowSkuPop:true, 
      goBuyType:buytype
    })
  },
  /**
   * 计算当前商品的所有的库存量
   */
  getAllSkuStock:function(skus){
    var count = 0
    for (var index in skus){
      var left_count = skus[index].leftCount
      count += left_count
    }
    console.log('skuStock===',count)
    this.setData({ skuStock: count})
  },
  swiper_bindchange: function (t) {
    var a = t.detail.current;
    this.setData({
      currentState: a + 1 + "/" + this.data.imgUrls.length,
      showSwiperNum: a + 2 > this.data.imgUrls.length ? this.data.imgUrls.length : a + 2,
      autoplay: !0
    });
  },
  preImg: function (t) {
    console.log("preSunImg",t)
    var a = t.currentTarget.dataset.imageindex, e = t.currentTarget.dataset.imgdata || [];
    var c = [];
    for(var index in e){
      c.push(e[index].imgUrl)
    }
    common_Js.preImg(a,c)
  },
  onClickSku:function(t){
    // console.log('onClickSku',t);
    console.log('dataset',t.currentTarget.dataset)
    var dataset = t.currentTarget.dataset;
    var that = this;
    var attrIndex = dataset.attrIndex;
    var valueIndex = dataset.valueIndex;
    that.data.productAttr[attrIndex].chooseValueIndex = valueIndex;
    that.data.productAttr[attrIndex].chooseValue = that.data.productAttr[attrIndex].attrValueArr[valueIndex];

    console.log('that.data.productAttr[attrIndex].chooseValue',that.data.productAttr[attrIndex].chooseValue)
    console.log('that.data.productAttr',that.data.productAttr)
    // console.log('that.data.product',that.data.product.productValue[])
    var sku_txt = that.checkSkuTxt(attrIndex,valueIndex);
    
    that.setData({
      productAttr: that.data.productAttr,
      chooseSkuTxt: sku_txt
    })
    that.getChooseSkuAttr()
  },
  checkSkuTxt: function (attrIndex,valueIndex) {
    var that = this;
    var txt = ''
    for (var index in this.data.productAttr) {
      console.log('index',index)
      var attr = this.data.productAttr[index];
      console.log('attr.attrValue[index]',attr.attrValue[index])

      // attr.attrValue[valueIndex].check = false;
      if(attr.chooseValueIndex < 0){
        txt = '';
        break;
      }else{
        txt += attr.chooseValue + ",";
        // attr.attrValue[index].check = true;
      }
      var attrValue = attr.attrValue
      for(var vIndex in attrValue){
        attrValue[vIndex].check = false;
        if(vIndex == valueIndex){
          attr.attrValue[vIndex].check = true;
        }
      }
    }

    if(txt!=''){
      txt = txt.substring(0,txt.length - 1);
      var sku = that.data.productValue[txt];
      if(sku!=undefined){
        console.log('sku',sku)
        that.setData({
          isCanPay:1,
          skuMaxCount: sku.stock,
          chooseSkuTxt: sku.sku,
          totalPrice:sku.price,
        })
        that.data.chooseSku = sku;
        console.log('sku',sku);
        
        that.data.chooseSkuCount = 1;
        that.setData({
            chooseSkuCount:1,
            skuMaxCount: sku.stock,
        })
        console.log('chooseSkuCount', that.data.chooseSkuCount)
        console.log('sku.stock', sku.stock)
      }else{
        //   Toast("无货")
          that.setData({
            isCanPay:0,
            skuMaxCount: 0,
            // chooseSkuTxt: "当前规格暂时无货",
            totalPrice:"当前规格暂时无货",
          })
      }
    }
    return txt;
  },
  getChooseSkuAttr:function(){
    var that = this
    var skuattr = '';
    for (var index in that.data.productAttr){
      skuattr += that.data.productAttr[index].check_value_id + ',';
    }
    if (skuattr != ''){
      skuattr = skuattr.substring(0, skuattr.length - 1)
    }
    that.data.chooseSkuId = skuattr
  },
  //修改购买数量
  skuCountChange({ detail }) {
    var that = this
    console.log('skuCountChange',detail)
    console.log('that.data.chooseSku.price',that.data.chooseSku.price)
    
    if(that.data.chooseSku.price == undefined){
      Toast.fail('请选择规格');
      that.setData({ chooseSkuCount: detail - 1 })
      return;
    }
    var isall_check = that.isAllCheck()
    if (isall_check) {
      that.setData({ chooseSkuCount: detail })
      that.setData({
        totalPrice:  Math.round(detail * that.data.chooseSku.price*100)/100
      })
    } else {//未选择分类规格， 提示请选择
      Toast.fail('请选择规格');
    }
  },
  getClickPrice: function(count){
    var that = this
    var skus = that.data.skus
    var price = 0.00
    for(var index in skus){
      console.log('that.data.chooseSkuAttr', that.data.chooseSkuAttr)
      console.log('skus[index].skuAttr', skus[index].skuAttr)
      if (that.data.chooseSkuAttr == skus[index].skuAttr){
        price = skus[index].price
        that.setData({
          skuStock: skus[index].leftCount,
          chooseSkuImg: skus[index].imgUrl,
          totalPrice: Math.round(price * that.data.chooseSkuCount*100)/100 
        })
      }
    }
  },
  closeSku: function () {
    this.setData({  isShowSkuPop : false  })
  },
  goUserSaid: function () {
    wx.navigateTo({ url: '/pages/order/userSaid/index?id=' + this.data.id })
  },
  goBuy:function(e){
    var that = this;
    console.log('chooseSkuId', that.data.chooseSkuId)
    console.log('chooseSkuCount', that.data.chooseSkuCount)
    var phone_num = app.getStorageSync("phone_num");
    var isLogin = app.getStorageSync("isLogin");
    if (isLogin == 1) {
        if(phone_num == undefined || phone_num == ''){
            this.handlePhoneNum();
        }else{
            if(this.data.chooseSku.id > 0){
                if(this.data.chooseSkuCount <= 0){
                  Toast.fail('数量不能为0');
                  return;
                }
                that.setData({ visibleModal: false });
                this.onHttpBuy();
                // Toast('暂未开通')
            }else{
                Toast.fail('请选择规格');
                return;
            }
        }

    }else{
        wx.navigateTo({
            url: '/pages/login/index',
          })
    }
  },
  handlePhoneNum(){
    var that = this;
    var message = "请先绑定手机号后再进行购买哟~"
    Dialog.confirm({
      title: '温馨提醒',
      message
    }).then(() => {
      wx.navigateTo({
        url: '/pages/account/index?from_type=product',
      })
    })
    .catch(() => {
      Dialog.close();
    });
  },
  buySubmit: function (t) {
    var that = this
    console.log('buySubmit t', t)
    that.setData({ visibleModal: false });
    if(t.detail.index == 1){
      // that.onHttpBuy()
      Toast('暂未开通')
    }
  },
  isAllCheck:function(){
    var isall_check = true
    for (var index in this.data.categorys) {
      if (this.data.categorys[index].check_value_id == '') {
        isall_check = false
      }
    }
    return isall_check;
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpBuy: function () {
    var that = this;
    console.log('that.data.product',that.data.product)
    console.log('that.data.product.saleType',that.data.product.saleType)
    var orderType = that.data.product.saleType == 0 ?  0 : 3;
    console.log('orderType',orderType)
    fetchApi.httpPost('/product/order/addOrderBuyNow', {
      attr_value_id: that.data.chooseSku.id,
      count: that.data.chooseSkuCount,
      order_type: orderType, //  积分商品订单
      ag_id:that.data.ag_id,
    }, function (res) {
      console.log("购买商品 ", res)
      if (res.data.code == 0) {
        var orderId = res.data.data
        wx.redirectTo({
          url: '/pages/pay/paySubmit/index?order_id=' + orderId
        })
      } else {
        console.log("购买商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  getSkuIdBySkuAttr:function(){
    var that = this
    var skuid = 0;
    for(var index in that.data.skus){
      if (that.data.chooseSkuId == that.data.skus[index].skuAttr){
        skuid = that.data.skus[index].id
      }
    }
    return skuid;
  },
  goAddCart(){
    var that = this
    console.log('chooseSkuId', that.data.chooseSkuId)
    console.log('chooseSkuCount', that.data.chooseSkuCount)
    var phone_num = app.getStorageSync("phone_num");
    var isLogin = app.getStorageSync("isLogin");
    if (isLogin == 1) {
        if(phone_num== undefined || phone_num == ''){
            this.handlePhoneNum();
        }else{
            if(this.data.chooseSku.id > 0){
                if(this.data.chooseSkuCount <= 0){
                Toast.fail('数量不能为0');
                return;
                }
                that.setData({ isShowSkuPop: false });
                this.onHttpAddCart();
            }else{
                Toast.fail('请选择规格');
                return;
            }
        }
    }else{
        wx.navigateTo({
            url: '/pages/login/index',
        })
    }    
  },
  /**
   *  添加到购物车获取页面数据的 http请求
   */
  onHttpAddCart: function () {
    var that = this;
    fetchApi.httpPost('/product/addCart', {
      product_id: that.data.id,
      attr_value_id:that.data.chooseSku.id,
      count: that.data.chooseSkuCount,
      ag_id:that.data.ag_id,
    }, function (res) {
      console.log("添加到购物车商品 ", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg)
        var count = res.data.data;
        that.setData({
          cart_count: count
        })
      } else {
        console.log("添加购物车商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  goCart(){
    wx.switchTab({
      url: '/pages/product/cart/index',
    })
  },
  goCollection(res){
    this.onHttpCollection(1)
  },
  goUnCollection(res){
    this.onHttpCollection(0)
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpCollection: function (is_collect) {
    var that = this
    var url = "";
    if(is_collect == 0){//当前为已收藏   执行取消收藏
      url = '/user/collection/delete';
    }else{//当前为未收藏   执行收藏
      url = '/user/collection/add';
    }
    fetchApi.httpPost(url, {
      product_id: that.data.id,
      collection_type: 0 //  商品收藏
    }, function (res) {
      console.log("收藏商品 ", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg)
        
        if(is_collect == 0){//当前为已收藏   执行取消收藏
          that.setData({
            isCollect: false
          })
        }else{//当前为未收藏   执行收藏
          that.setData({
            isCollect: true
          })
        }

      } else {
        console.log("收藏商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    var product_id = this.data.id;
    var ag_id = app.getStorageSync("ag_id");
    console.log( "转发成功 ag_id",ag_id)
    var title = "【抢购价￥"+ that.data.product.price+"】" + that.data.product.storeName;
    return {
      title: title,
      path: '/pages/product/detail/index?id='+product_id+'&ag_id='+ag_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },
})
